package com.group.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * com.gxa.filter
 * User: 恩哲欣
 * Date: 2024/10/18 20:47
 * Motto: Where there is a will, there is a way!
 * Description:
 * Version: V1.0
 */
public class CORSFilter implements Filter {
    // 浏览器默认不允许跨域访问
    // 配置跨域过滤器
    // 跨域访问：协议、域名、接口要保持一致，否则就是跨域访问
    // 告诉浏览器允许跨域访问（其中一种解决方式）
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;

        /* 允许跨域的主机地址 */
        response.setHeader("Access-Control-Allow-Origin", "*");
        /* 允许跨域的请求方法GET, POST, HEAD 等 */
        response.setHeader("Access-Control-Allow-Methods", "*");
        /* 重新预检验跨域的缓存时间 (s) */
        response.setHeader("Access-Control-Max-Age", "3600");
        /* 允许跨域的请求头 */
        response.setHeader("Access-Control-Allow-Headers", "*");
        /* 是否携带cookie */
        response.setHeader("Access-Control-Allow-Credentials", "true");

        //判断前端发送的是否是预请求，如果是，直接返回，并且告诉他允许的请求方式
        if("OPTIONS".equalsIgnoreCase(request.getMethod()))
            return;

        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}
